import React, {
  Component,
  useState,
  useRef,
  createContext,
  useContext,
  useEffect,
} from "react";
import classNames from "classnames";
import "./index.css";
/* 
  1.使用createContext()方法创建一个上下文对象Ctx
  2.在顶层组件(Parent)中通过Ctx.Provider组件提供数据
  3.在顶层组件(Son)中通过useContext钩子函数获取消费数据
*/

export default function Parent() {
  let [list, setList] = useState([]);
  let [num, setNum] = useState(0);
  let [count, setCount] = useState(0);
  let [flag, setFlag] = useState(true);
  //1.初始化+组件更新
  useEffect(() => {
    console.log("只要组件更新都会执行");
  });
  //2.传入空数组依赖，初始化执行一次
  useEffect(() => {
    fetch(" https://song.sgang.xyz/song/list?name=").then((res) => {
      res.json().then((res) => {
        console.log(res.data);
        setList(res.data.list);
      });
    });
  }, []);
  //3.传入特定依赖性   初始+依赖项变化时执行
  useEffect(() => {
    console.log("特定依赖性会发生执行");
  }, [num]);
  return (
    <>
      <h1>useEffect</h1>
      <p>count:{count}</p>
      <p>num:{num}</p>
      <button onClick={() => setCount(count + 1)}>count++</button>
      <button onClick={() => setNum(num + 1)}>num++</button>
      {list.map((item) => (
        <div key={item.id}>{item.name}</div>
      ))}
      <div>{flag && <Child></Child>}</div>
      <button onClick={() => setFlag(flag ? false : true)}>
        显示隐藏child
      </button>
    </>
  );
}
function Child() {
  useEffect(() => {
    let timer = setInterval(() => {
      console.log("setinterval");
    }, 1000);
    return ()=>{  //清除副作用  组件卸载时
      clearInterval(timer)
    }
  }, []);
  return (
    <>
      <div>child组件</div>
    </>
  );
}
